package com.example.pruebaHttp;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;

import android.app.ExpandableListActivity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.datas.Child;
import com.example.datas.Comunicador;
import com.example.datas.Constants;
import com.example.datas.MemoryCache;
import com.example.datas.Parent;
import com.example.datas.SummonerData;

public class RecentGamesActivity extends ExpandableListActivity {
	// Initialize variables
	private int ParentClickStatus = -1;
	private int ChildClickStatus = -1;

	private ArrayList<Parent> parents;
	private String splashURL;

	private String[] itemURL = new String[7];
	private Semaphore mutex = new Semaphore(0);
	private Semaphore mutex2 = new Semaphore(1);
	private SummonerData summonerData;
	Bitmap splashBM;
	Bitmap itemBM;
	private MemoryCache cache = new MemoryCache();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		summonerData = Comunicador.getCommunicador();
		Resources res = this.getResources();
		Drawable devider = res.getDrawable(R.drawable.headerbg);

		// Set ExpandableListView values

		getExpandableListView().setGroupIndicator(null);
		getExpandableListView().setDivider(devider);
		getExpandableListView().setChildDivider(devider);
		getExpandableListView().setDividerHeight(1);
		registerForContextMenu(getExpandableListView());

		// Creating static data in arraylist
		final ArrayList<Parent> dummyList = summonerData.getRecentGames();

		// Adding ArrayList data to ExpandableListView values
		loadHosts(dummyList);
	}

	private void loadHosts(final ArrayList<Parent> newParents) {
		if (newParents == null)
			return;

		parents = newParents;

		// Check for ExpandableListAdapter object
		if (this.getExpandableListAdapter() == null) {
			// Create ExpandableListAdapter Object
			final MyExpandableListAdapter mAdapter = new MyExpandableListAdapter();

			// Set Adapter to ExpandableList Adapter
			this.setListAdapter(mAdapter);
		} else {
			// Refresh ExpandableListView data
			((MyExpandableListAdapter) getExpandableListAdapter())
					.notifyDataSetChanged();
		}
	}

	/**
	 * A Custom adapter to create Parent view (Used grouprow.xml) and Child
	 * View((Used childrow.xml).
	 */
	private class MyExpandableListAdapter extends BaseExpandableListAdapter {

		private LayoutInflater inflater;

		public MyExpandableListAdapter() {
			// Create Layout Inflator
			inflater = LayoutInflater.from(RecentGamesActivity.this);
		}

		// This Function used to inflate parent rows view

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parentView) {
			final Parent parent = parents.get(groupPosition);

			// Inflate grouprow.xml file for parent rows
			convertView = inflater.inflate(R.layout.list_parent, parentView,
					false);

			// Get grouprow.xml file elements and set values
			((TextView) convertView.findViewById(R.id.kda0)).setText(parent
					.getKda());
			((TextView) convertView.findViewById(R.id.gameType))
					.setText(/* Constants.getGameMode( */parent.getGameMode()/* ) */
							+ "("
							+ /* Constants.getGameSubType( */parent.getGameType()/* ) */
							+ ")");
			if (parent.getVictory()) {
				((TextView) convertView.findViewById(R.id.win0))
						.setText("Victory");
				((TextView) convertView.findViewById(R.id.win0))
						.setTextColor(Color.parseColor("#088A08"));
			} else {
				((TextView) convertView.findViewById(R.id.win0))
						.setText("Defeat");
				((TextView) convertView.findViewById(R.id.win0))
						.setTextColor(Color.parseColor("#8A0808"));
			}
			((TextView) convertView.findViewById(R.id.map)).setText(""+parent.getMap());
			ImageView image = (ImageView) convertView
					.findViewById(R.id.splash0);
			ImageView item0 = (ImageView) convertView.findViewById(R.id.item0);
			ImageView item1 = (ImageView) convertView.findViewById(R.id.item1);
			ImageView item2 = (ImageView) convertView.findViewById(R.id.item2);
			ImageView item3 = (ImageView) convertView.findViewById(R.id.item3);
			ImageView item4 = (ImageView) convertView.findViewById(R.id.item4);
			ImageView item5 = (ImageView) convertView.findViewById(R.id.item5);
			ImageView item6 = (ImageView) convertView.findViewById(R.id.item6);

			// Splash image to retrieve;
			splashURL = "http://ddragon.leagueoflegends.com/cdn/"
					+ summonerData.getDDVersion() + "/img/champion/"
					+ Constants.getChampionName(parent.getSplash()) + ".png";
			// Icons items urls
			for (int i = 0; i < 7; i++) {
				if (parent.getItem(i) != 0)
					itemURL[i] = "http://ddragon.leagueoflegends.com/cdn/"
							+ summonerData.getDDVersion() + "/img/item/"
							+ parent.getItem(i) + ".png";
			}

			TareaWSConsulta tarea = new TareaWSConsulta();
			tarea.execute();
			try {
				mutex.acquire();

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			mutex2.release();

			image.setImageBitmap(cache.get(splashURL));

			if (parent.getItem(0) != 0)
				item0.setImageBitmap(cache.get(itemURL[0]));
			if (parent.getItem(1) != 0)
				item1.setImageBitmap(cache.get(itemURL[1]));
			if (parent.getItem(2) != 0)
				item2.setImageBitmap(cache.get(itemURL[2]));
			if (parent.getItem(3) != 0)
				item3.setImageBitmap(cache.get(itemURL[3]));
			if (parent.getItem(4) != 0)
				item4.setImageBitmap(cache.get(itemURL[4]));
			if (parent.getItem(5) != 0)
				item5.setImageBitmap(cache.get(itemURL[5]));
			if (parent.getItem(6) != 0)
				item6.setImageBitmap(cache.get(itemURL[6]));

			return convertView;
		}

		// This Function used to inflate child rows view
		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parentView) {
			final Parent parent = parents.get(groupPosition);
			final Child child = parent.getChildren();

			// Inflate childrow.xml file for child rows
			convertView = inflater.inflate(R.layout.list_child, parentView,
					false);
			TextView wardsPlaced = ((TextView) convertView
					.findViewById(R.id.wardsPlaced));
			// put the wards placed color.
			if (child.getWardsPlaced() < 5) {
				// Menos de 5 wards puestos.
				wardsPlaced.setTextColor(Color.RED);
			} else {
				if (child.getWardsPlaced() < 10) {
					// Entre 5 y 10 wards.
					wardsPlaced.setTextColor(Color.parseColor("#088A08"));

				} else {
					if (child.getWardsPlaced() < 20) {
						// entre 10 y 20.
						wardsPlaced.setTextColor(Color.BLUE);

					} else {
						// mas de 20 wards.
						wardsPlaced.setTextColor(Color.MAGENTA);

					}
				}
			}
			wardsPlaced.setText("" + child.getWardsPlaced());
			TextView wardsKilled = ((TextView) convertView
					.findViewById(R.id.wardsKilled));
			// Put the wards killed color
			if (child.getWardsKilled() < 1) {
				// Menos de 1 wards quitados.
				wardsKilled.setTextColor(Color.RED);
			} else {
				if (child.getWardsKilled() < 3) {
					// Entre 1 y 3 wards.
					wardsKilled.setTextColor(Color.parseColor("#088A08"));

				} else {
					if (child.getWardsKilled() < 8) {
						// entre 3 y 6.
						wardsKilled.setTextColor(Color.BLUE);

					} else {
						// mas de 8 wards.
						wardsKilled.setTextColor(Color.MAGENTA);

					}
				}
			}
			wardsKilled.setText("" + child.getWardsKilled());

			TextView CC = (TextView) convertView.findViewById(R.id.ccDealt);
			CC.setText("" + CC.getText() + child.getCcDealt());
			TextView goldEarn = (TextView) convertView
					.findViewById(R.id.goldEarned);
			goldEarn.setText("" + child.getGoldEarned());
			TextView crit = (TextView) convertView
					.findViewById(R.id.largestCrit);
			crit.setText("" + crit.getText() + child.getLargestCrit());
			TextView minions = (TextView) convertView
					.findViewById(R.id.minionsKilled);
			minions.setText(""
					+ (child.getMinionsSlain() + child.getMonstersSlain())
					+ "(" + child.getMinionsSlain() + "/"
					+ child.getMonstersSlain() + ")"+minions.getText());
			TextView mins = (TextView) convertView.findViewById(R.id.timePlayed);
			mins.setText(""+mins.getText()+child.getTimePlayed()+" min.");
			TextView killingSpree = (TextView) convertView.findViewById(R.id.killingSpree);
			killingSpree.setText(""+killingSpree.getText()+child.getKillingSpree());
			TextView damageTaken = (TextView) convertView.findViewById(R.id.damageTaken);
			damageTaken.setText(""+damageTaken.getText()+child.getTotalDamageTaken());
				
			((TextView) convertView.findViewById(R.id.magicDamageChamp)).setText(""+child.getMagicDamageChampion());
			((TextView) convertView.findViewById(R.id.totalDamageChamp)).setText(""+child.getTotalDamageToChampions());
			((TextView) convertView.findViewById(R.id.physicalDamageChamp)).setText(""+child.getPhysicalDamageChampion());
			
			((TextView) convertView.findViewById(R.id.turretsKilled)).setText(""+child.getTurretsKilled()+" ");
			((TextView) convertView.findViewById(R.id.inhibsKilled)).setText(""+child.getBarracksKilled()+" ");
			
			return convertView;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return parents.get(groupPosition).getChildren();
		}

		// Call when child row clicked
		@Override
		public long getChildId(int groupPosition, int childPosition) {
			/****** When Child row clicked then this function call *******/
			if (ChildClickStatus != childPosition) {
				ChildClickStatus = childPosition;

			}

			return childPosition;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return parents.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return parents.size();
		}

		// Call when parent row clicked
		@Override
		public long getGroupId(int groupPosition) {

			if (groupPosition == 2 && ParentClickStatus != groupPosition) {

				// Alert to user

			}

			ParentClickStatus = groupPosition;
			if (ParentClickStatus == 0)
				ParentClickStatus = -1;

			return groupPosition;
		}

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}

		@Override
		public boolean isEmpty() {
			return ((parents == null) || parents.isEmpty());
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public boolean areAllItemsEnabled() {
			return true;
		}
	}

	private class TareaWSConsulta extends AsyncTask<String, Integer, Boolean> {

		protected Boolean doInBackground(String... params) {
			boolean resul = true;
			try {
				mutex2.acquire();
				if (cache.get(splashURL) == null) {
					splashBM = BitmapFactory
							.decodeStream((InputStream) new URL(splashURL)
									.getContent());
					cache.put(splashURL, splashBM);
				}
				for (int i = 0; i < 7; i++) {
					if (cache.get(itemURL[i]) == null && itemURL[i] != null) {
						itemBM = BitmapFactory
								.decodeStream((InputStream) new URL(itemURL[i])
										.getContent());
						cache.put(itemURL[i], itemBM);
					}

				}

				mutex.release();

			} catch (Exception e) {
				e.printStackTrace();
			}

			return resul;
		}

		protected void onPostExecute(Boolean result) {
			// void method :(
		}

	}

}
